package com.dhq.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 使用线程局部变量列表避免线程间共享数据污染
 */
public class ThreadSharedDataIsolate {
    private static int data=0;

    private static Map<Long,Integer> threadLocalMap = new HashMap<Long,Integer>();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //为了避免布局变量在存入线程布局变量列表时被污染，将获取随机数据和存放数据的业务同步
                    //如果扩大同步的范围，即使不使用线程布局变量列表也可以避免线程污染
                    //扩大同步的特点是，1，效率下降；2，这里主要是为展示ThreadLocal类做铺垫，所以，没有使用扩大同步
                    synchronized (threadLocalMap){
                        data = new Random().nextInt();
                        threadLocalMap.put(Thread.currentThread().getId(),data);
                    }
                    System.out.println("当前线程ID："+Thread.currentThread().getId()+";线程Name："+Thread.currentThread().getName());
                    System.out.println(Thread.currentThread().getName()+":"+threadLocalMap.get(Thread.currentThread().getId()));
                    new A().get();
                    new B().get();
                }
            }).start();
        }
    }

    static class A{
        public void get(){
            int data = threadLocalMap.get(Thread.currentThread().getId());
            System.out.println("A == "+Thread.currentThread().getName()+": "+data);
        }
    }

    static class B{
        public void get(){
            int data = threadLocalMap.get(Thread.currentThread().getId());
            System.out.println("B == "+Thread.currentThread().getName()+": "+data);
        }
    }
}
